#include "EditConfigDlg.h"
#include "ui_editconfigdlg.h"

EditConfigDlg::EditConfigDlg(QString id,QList<DictData> dictList,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::EditConfigDlg)
{
    ui->setupUi(this);
    this->id = id;
    this->dictList = dictList;
    if(id != "0"){
        setWindowTitle("修改参数");
        init();
    }else{
        setWindowTitle("添加参数");
    }
    ui->radioButton->setText(dictList.at(0).dictLabel);
    ui->radioButton_2->setText(dictList.at(1).dictLabel);
}

EditConfigDlg::~EditConfigDlg()
{
    delete ui;
}

void EditConfigDlg::init()
{
    r = paramsSetApi.getById(id);
    QByteArray bytes = r->readAll().data();
    if(bytes.isEmpty()){
        QMessageBox::warning(0,"提示","服务器连接失败");
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(bytes).object();
    if(200 != obj.value("code").toInt()){
        QMessageBox::warning(0,"提示",obj.value("msg").toString());
        return;
    }
    config = SysConfig::toSysConfig(obj.value("data").toObject());
    ui->lineEdit_paramName->setText(config->configName);
    ui->lineEdit_paramKeyName->setText(config->configKey);
    ui->lineEdit_paramKeyValue->setText(config->configValue);
    config->configType == "Y" ? ui->radioButton->setChecked(1) : ui->radioButton_2->setChecked(1);
    ui->textEdit->setText(config->remark);
}

void EditConfigDlg::on_btn_cancel_clicked()
{
    this->close();
}


void EditConfigDlg::on_btn_ok_clicked()
{
    if(ui->lineEdit_paramKeyName->text().isEmpty()){
        ui->lineEdit_paramKeyName->setStyleSheet("border:1px solid red;");
        return;
    }
    if(ui->lineEdit_paramName->text().isEmpty()){
        ui->lineEdit_paramName->setStyleSheet("border:1px solid red;");
        return;
    }
    if(ui->lineEdit_paramKeyValue->text().isEmpty()){
        ui->lineEdit_paramKeyValue->setStyleSheet("border:1px solid red;");
        return;
    }
    ui->lineEdit_paramKeyName->setStyleSheet("");
    ui->lineEdit_paramName->setStyleSheet("");
    ui->lineEdit_paramKeyValue->setStyleSheet("");
    if(id == "0"){
        config = new SysConfig;
    }
    config->configName = ui->lineEdit_paramName->text();
    config->configKey = ui->lineEdit_paramKeyName->text();
    config->configValue = ui->lineEdit_paramKeyValue->text();
    config->configType = ui->radioButton->isChecked() ? "Y" : "N";
    config->remark = ui->textEdit->toPlainText();
    if(id == "0"){
        r = paramsSetApi.add(config);
    }else{
        r = paramsSetApi.update(config);
    }
    QByteArray bytes = r->readAll().data();
    if(bytes.isEmpty()){
        QMessageBox::warning(0,"提示","服务器连接失败");
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(bytes).object();
    QMessageBox::warning(0,"提示",obj.value("msg").toString());
    if(200 != obj.value("code").toInt()){
        return;
    }
    emit success();
    this->close();
}

